import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class DamageManageFrame extends JFrame {
    private JTable damageTable;
    private DefaultTableModel tableModel;

    public DamageManageFrame() {
        setTitle("报损管理");
        setSize(800, 500);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("报损单号");
        tableModel.addColumn("货物编号");
        tableModel.addColumn("货物名称");
        tableModel.addColumn("报损数量");
        tableModel.addColumn("报损日期");
        tableModel.addColumn("经手人");

        damageTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(damageTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加报损");
        JButton deleteBtn = new JButton("删除记录");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadDamageData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new DamageEditDialog(null).setVisible(true);
            loadDamageData();
        });

        deleteBtn.addActionListener(e -> deleteDamage());
        refreshBtn.addActionListener(e -> loadDamageData());
    }

    private void loadDamageData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT r.*, g.dname FROM report_damages r JOIN goods g ON r.dno = g.dno")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("rno"),
                        rs.getString("dno"),
                        rs.getString("dname"),
                        rs.getInt("rnum"),
                        rs.getDate("rdate"),
                        rs.getString("rpeople")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteDamage() {
        int selectedRow = damageTable.getSelectedRow();
        if (selectedRow >= 0) {
            String rno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除报损单 " + rno + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM report_damages WHERE rno = ?")) {

                    pstmt.setString(1, rno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadDamageData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class DamageEditDialog extends JDialog {
    private JTextField rnoField, dnoField, rnumField, rpeopleField;
    private JComboBox<String> dnameCombo;
    private JSpinner rdateSpinner;
    private boolean isEditMode;
    private DefaultComboBoxModel<String> goodsComboModel;

    public DamageEditDialog(String rno) {
        if (rno == null) {
            setTitle("添加报损单");
            isEditMode = false;
        } else {
            setTitle("修改报损单");
            isEditMode = true;
        }

        setSize(500, 300);
        setModal(true);
        setLocationRelativeTo(null);

        // 初始化商品下拉框模型
        goodsComboModel = new DefaultComboBoxModel<>();
        loadGoodsData();

        JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("报损单号:"));
        rnoField = new JTextField();
        if (isEditMode) rnoField.setEditable(false);
        panel.add(rnoField);

        panel.add(new JLabel("货物名称:"));
        dnameCombo = new JComboBox<>(goodsComboModel);
        dnameCombo.addActionListener(e -> updateDnoField());
        panel.add(dnameCombo);

        panel.add(new JLabel("货物编号:"));
        dnoField = new JTextField();
        dnoField.setEditable(false);
        panel.add(dnoField);

        panel.add(new JLabel("报损数量:"));
        rnumField = new JTextField();
        panel.add(rnumField);

        panel.add(new JLabel("报损日期:"));
        rdateSpinner = new JSpinner(new SpinnerDateModel());
        JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(rdateSpinner, "yyyy-MM-dd");
        rdateSpinner.setEditor(dateEditor);
        panel.add(rdateSpinner);

        panel.add(new JLabel("经手人:"));
        rpeopleField = new JTextField();
        panel.add(rpeopleField);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveDamage());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadDamageData(rno);
        } else {
            // 新建时默认日期为当天
            rdateSpinner.setValue(new java.util.Date());
        }
    }

    private void loadGoodsData() {
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT dno, dname FROM goods")) {

            while (rs.next()) {
                goodsComboModel.addElement(rs.getString("dname") + " (" + rs.getString("dno") + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载货物数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateDnoField() {
        String selected = (String) dnameCombo.getSelectedItem();
        if (selected != null) {
            // 从"货物名称 (货物编号)"格式中提取编号
            String dno = selected.substring(selected.lastIndexOf("(") + 1, selected.lastIndexOf(")"));
            dnoField.setText(dno);
        }
    }

    private void loadDamageData(String rno) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "SELECT r.*, g.dname FROM report_damages r JOIN goods g ON r.dno = g.dno WHERE r.rno = ?")) {

            pstmt.setString(1, rno);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                rnoField.setText(rs.getString("rno"));
                rnumField.setText(String.valueOf(rs.getInt("rnum")));
                rpeopleField.setText(rs.getString("rpeople"));
                rdateSpinner.setValue(rs.getDate("rdate"));

                // 设置选中的货物
                String dnameWithDno = rs.getString("dname") + " (" + rs.getString("dno") + ")";
                dnameCombo.setSelectedItem(dnameWithDno);
                dnoField.setText(rs.getString("dno"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载报损数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveDamage() {
        String rno = rnoField.getText().trim();
        String dno = dnoField.getText().trim();
        String rnumStr = rnumField.getText().trim();
        String rpeople = rpeopleField.getText().trim();
        java.util.Date rdate = (java.util.Date) rdateSpinner.getValue();

        // 验证输入
        if (rno.isEmpty() || dno.isEmpty() || rnumStr.isEmpty() || rpeople.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段都必须填写", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int rnum;
        try {
            rnum = Integer.parseInt(rnumStr);
            if (rnum <= 0) {
                JOptionPane.showMessageDialog(this, "报损数量必须大于0", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "报损数量必须是整数", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE report_damages SET dno=?, rnum=?, rdate=?, rpeople=? WHERE rno=?");
                pstmt.setString(1, dno);
                pstmt.setInt(2, rnum);
                pstmt.setDate(3, new java.sql.Date(rdate.getTime()));
                pstmt.setString(4, rpeople);
                pstmt.setString(5, rno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO report_damages (rno, dno, rnum, rdate, rpeople) VALUES (?, ?, ?, ?, ?)");
                pstmt.setString(1, rno);
                pstmt.setString(2, dno);
                pstmt.setInt(3, rnum);
                pstmt.setDate(4, new java.sql.Date(rdate.getTime()));
                pstmt.setString(5, rpeople);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}